package com.liveneo.adapter.base.support;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liveneo.system.base.utils.Constant;

/**
 * 所有服务类的超级父类
 */
public abstract class BaseService<D extends BaseMapper<T>, T extends BaseEntity> {
    @Autowired
    protected D mapper;

    /**
     * 根据ID查询一条数据
     * @param id
     * @return
     */
    public T queryById(String id) throws Exception {
        return mapper.selectByPrimaryKey(id);
    }

    /**
     * 分页查询列表 pageHelper PageInfo 分页参数，起始页码 每一页的大小， 排序
     * @param entity
     * @param pageParam
     * @return
     */
    public PageInfo<T> queryListWithPage(T entity, PageParam pageParam) throws Exception {
        // 判断是否含有排序的字符串
        if (StringUtils.isNotBlank(pageParam.getOrderBy())) {
            PageHelper.orderBy(pageParam.getOrderBy());
        }
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        List<T> resultList = readDataList();
        return new PageInfo<T>(resultList);
    }

    protected List<T> readDataList() {
        return new ArrayList<T>();
    }

    /**
     * 保存数据 id为空时，执行新增，id不为空，修改
     * @param entity
     * @return
     */
    public boolean save(T entity) throws Exception {
        // 判断Id是否为空
        // "               "
        int res = 0;
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(Constant.MYSQL_UUID);
            res = mapper.insert(entity);
        } else {
            res = mapper.updateByPrimaryKey(entity);
        }
        return res > 0;
    }

    /**
     * 删除数据
     * @param entity
     * @return
     */
    public boolean delete(T entity) throws Exception {
        int res = mapper.deleteByPrimaryKey(entity.getId());
        return res > 0;
    }
    
}
